package com.example.baiduapi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.baiduapi.Mapper.mysqlMapper.UserMapper;
import com.example.baiduapi.Util.*;
import com.example.baiduapi.pojo.UserInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    @Resource
    private zhenziSMS sms;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisUtils redisUtils;
    public String commOnLogin2(String username,String password){
        System.out.println(username+":"+password);
        UserInfo userInfoByID = userMapper.getUserInfoByID(username);
        if(userInfoByID!=null){
            if(userInfoByID.getPassword().equals(password)){
                return "true";
            }
            return "false";
        }else{
            return "false";
        }
    }
    public UserInfo commOnLogin(String loginName,String password) throws Exception{
        String userInfo = redisUtils.get(loginName);
        UserInfo userInfoByID = null;
        // 如果redis不存在则为首次登录查询数据库
        if (StringUtils.isEmpty(userInfo)) {
            userInfoByID = userMapper.getUserInfoByLoginName(loginName);
            redisUtils.set(loginName,JSON.toJSONString(userInfoByID));
        }else {
            userInfoByID = JSON.parseObject(userInfo,new TypeReference<UserInfo>() {});
        }
        // 用户存在做账号密码校验
        if(userInfoByID!=null){
            if(userInfoByID.getPassword().equals(password)){
                Integer number = Integer.valueOf(userInfoByID.getLoginNumber() == null ? 0 : userInfoByID.getLoginNumber())+1;
                userInfoByID.setLoginNumber(number); // 添加登录数量
                redisUtils.set(loginName,JSON.toJSONString(userInfoByID));
                return userInfoByID.setPassword(null);
            }
            return null;
        }else{
            return null;
        }
    }

    /**
     * 下线用户
     * @param username 用户名
     * @param message 下线信息
     * @return
     */
    public Boolean commOffLogin(String username,String message){
        Map userTemp = JSON.parseObject(redisUtils.get(username),Map.class);
        if (StringUtils.isEmpty(userTemp)){
           return false;
        }
        userTemp.put("loginNumber",Integer.valueOf(userTemp.get("loginNumber").toString())+1);
        redisUtils.set(username,JSON.toJSONString(String.valueOf(userTemp)));
        return true;
    }

    /**
     * 短信登录
     * @param username 手机号
     * @param password 验证码
     * @return
     * @throws Exception
     */
    public UserInfo MessageLogin(String username,String password) throws Exception {
        /*String data = "{number=16608676369, success=true, appId=113588, messageId=fbe95866-c665-46c9-8365-344c3d19296a, templateParams=[Ljava.lang.String;@7e85b2d0, appSecret=ba1ae2a6-0592-4113-b522-08c3b3b1cb0d, templateId=12385}";
        redisUtils.set(username,data);*/
        String s = redisUtils.get(username);
        if (StringUtils.isEmpty(s) ){ // 验证码过期
            return null;
        }
        Map<String, String> messageInfo = null;
        try {
            System.out.println(s);
            messageInfo = JSON.parseObject(s, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }


        /*
            number = 16608676369,success =true,appId =113588,
            messageId =663abfbd -7a57 -4da9 -ada3 -20e124c73461,
            templateParams =[Ljava.lang.String;@7490a2f4,
            appSecret =ba1ae2a6 -0592-4113-b522 -08c3b3b1cb0d,
            templateId =12385*/
        System.out.println(messageInfo);

        if(messageInfo!=null){

            // 从redis中取出验证码判断验证码是否正确   sms.checkMessage();
            if(sms.checkMessage(messageInfo.get("messageId").toString(), password)){
                Integer userSize = userMapper.CountUserByPhone(username);
                if (userSize < 1){
                    userMapper.addUserInfo(username, password);
                }
                UserInfo getUserInfoByPhone = userMapper.getUserInfoByPhone(username);

                return getUserInfoByPhone.setPassword(null);// 短信验证码登录成功
            }
        }
        return null;// 短信验证码登录失败
    }


    public Map<String, Object> requestMessage(String username) throws Exception{
        Integer i = sms.checkBalance();
        Map<String, Object> stringObjectMap = new HashMap<String, Object>();
        if(i>0){
            stringObjectMap = sms.sendMessage(username, username);
        }
        System.out.println(stringObjectMap);
        /*{number=16608676369, success=true, appId=113588, messageId=fbe95866-c665-46c9-8365-344c3d19296a, templateParams=[Ljava.lang.String;@7e85b2d0, appSecret=ba1ae2a6-0592-4113-b522-08c3b3b1cb0d, templateId=12385}*/
        // 将验证码写入redis
        redisUtils.set(username+"reqMSM",JSON.toJSONString(stringObjectMap));
        // 验证码300秒过期
        redisUtils.expire(username, 300, TimeUnit.SECONDS);
        return stringObjectMap;
    }

    // 异步增加登录次数
    public void addLoginCount(String username){
        userMapper.updateLoginTimesByID(username);
    }
}
